﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZhwangTool
{
    /// <summary>
    /// FindFileUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class FindFileUserControl : UserControl
    {
        public FindFileUserControl()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ComBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        List<string> nameList = new List<string>();

        List<string> paths = new List<string>();

        ObservableCollection<FileInfo> sourceList_dataGrid1 = new ObservableCollection<FileInfo>();

        ObservableCollection<MyFileInfo> sourceList_dataGrid2 = new ObservableCollection<MyFileInfo>();



        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void ListFileButton_Click(object sender, RoutedEventArgs e)
        {
            //FileInfo fileInfo = new FileInfo("t");
            //fileInfo.Extension

            sourceList_dataGrid1.Clear();

            string path = textBox1.Text;

            if (System.IO.Directory.Exists(path)==false)
            {
                return;
            }
            
            #region 控制文件类型

            string p = "*";

            List<string> nameListInCurPath = new List<string>();

            nameListInCurPath = Getfiles(path, p, checkBox1.IsChecked);

            switch (comBox1.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".dwg")).ToList<string>();
                    break;
                case 2:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".xls") || x.EndsWith(".xlsx")).ToList<string>();
                    break;
                case 3:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".ppt") || x.EndsWith(".pptx")).ToList<string>();
                    break;
                case 4:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx")).ToList<string>();
                    break;
                case 5:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".pdf")).ToList<string>();
                    break;
                case 6:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".rar") || x.EndsWith(".zip") || x.EndsWith(".7z")).ToList<string>();
                    break;
                case 7:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx") || x.EndsWith(".dwg") || x.EndsWith(".ppt") ||
                     x.EndsWith(".pptx") || x.EndsWith(".xls") || x.EndsWith(".xlsx") || x.EndsWith("*.pdf")).ToList<string>();
                    break;
                case 8:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".jpg") || x.EndsWith(".JPG") || x.EndsWith(".BMP") || x.EndsWith(".bmp") || x.EndsWith(".png") || x.EndsWith(".PNG") ||
                    x.EndsWith(".jpeg") || x.EndsWith(".JPEG")).ToList<string>();
                    break;
                case 9:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".bak")).ToList<string>();
                    break;

                default:
                    break;
            }

            //if (comBox1.SelectedIndex == 0)
            //{
            //    p = @"*";

            //}
            //if (comBox1.SelectedIndex == 1)
            //{
            //    p = @"*.dwg";
            //}
            //if (comBox1.SelectedIndex == 2)
            //{
            //    p = "*.xls?";
            //}
            //if (comBox1.SelectedIndex == 3)
            //{
            //    p = @"*.ppt?";
            //}
            //if (comBox1.SelectedIndex == 4)
            //{
            //    p = @"*.doc?";
            //}
            //if (comBox1.SelectedIndex == 5)
            //{
            //    p = @"*.pdf";
            //}
            //if (comBox1.SelectedIndex == 6)
            //{
            //    p = @"*.rar";
            //}
            //if (comBox1.SelectedIndex == 7 || comBox1.SelectedIndex == 8)
            //{
            //    p = @"*";
            //}

            #endregion

            listBox1.Items.Clear();
            listBox1.Items.Add("仅满足文件类型的文件");
            foreach (string item in nameListInCurPath)
            {
                listBox1.Items.Add(item);
            }
            
            List<string> tmp_names = new List<string>();

            try
            {

                string[] tagS = containTag.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                List<string> containTagFileNames = new List<string>();

                #region  --处理文件名中包含关键字的情况

                //将包含给定字符串的文件名添加到给定的结合中

                foreach (string tmpFileName in nameListInCurPath)
                {
            
                    bool allWordsFound = true; // 假设所有单词都找到了，然后逐个检查
                    
                    foreach (string word in tagS)
                    {
                        if (!System.IO.Path.GetFileNameWithoutExtension(tmpFileName).Contains(word))
                        {
                            allWordsFound = false; // 如果发现某个单词不在字符串中，标记为未找到
                            //Console.WriteLine($"The word '{word}' was not found in the string.");
                            break; // 跳出循环，因为已经知道不是所有单词都找到了
                        }
                    }

                    if (allWordsFound)
                    {
                        containTagFileNames.Add(tmpFileName);
                    }

                }

                #endregion

                //SelectedIndex==0 表示不控制时间

                if (comBoxTime.SelectedIndex==0)
                {
                    sourceList_dataGrid1.Clear();

                    foreach (var item in containTagFileNames)
                    {
                        FileInfo fileInfo = new FileInfo(item);
                        
                        sourceList_dataGrid1.Add(fileInfo);
                    }

                    dataGrid1.ItemsSource = sourceList_dataGrid1.OrderBy(x=>x.Name);

                }

                //根据前面判断，此处需要处理控制时间范围

                #region --接下来处理给定日期范围内的文件

                if (startTimeDate.SelectedDate.Value==null|| endTimeDate.SelectedDate.Value==null)
                {
                    MessageBox.Show("未选定有效的起始日期和截止日期，跳过对时间复合型检查");
                    return;
                }
                #region 调整时间范围顺序，兼容起始日期晚于截止日期


                DateTime timeA = startTimeDate.SelectedDate.Value.Date;
                DateTime timeB = endTimeDate.SelectedDate.Value.Date;

                DateTime startTime = System.DateTime.Today;
                DateTime endTime = System.DateTime.Today;

                if (timeA >= timeB)
                {
                    startTime = timeB;
                    endTime = timeA;
                }
                else
                {
                    startTime = timeA;
                    endTime = timeB;
                }

                #endregion


                switch (comBoxTime.SelectedIndex)
                {
                    case 0:
                        break;
                    case 1:
                        containTagFileNames = containTagFileNames.Where(x => System.IO.File.GetLastWriteTime(x).Date >= startTime &&
                                                                             System.IO.File.GetLastWriteTime(x).Date <= endTime).ToList<string>();
                        break;

                    case 2:
                        containTagFileNames = containTagFileNames.Where(x => System.IO.File.GetCreationTime(x).Date >= startTime &&
                                                                             System.IO.File.GetCreationTime(x).Date <= endTime).ToList<string>();
                        break;

                    case 3:
                        containTagFileNames = containTagFileNames.Where(x => System.IO.File.GetLastAccessTime(x).Date >= startTime &&
                                                                             System.IO.File.GetLastAccessTime(x).Date <= endTime).ToList<string>();
                        break;

                    default:
                        break;
                }


                sourceList_dataGrid1.Clear();

                foreach (var item in containTagFileNames)
                {
                    FileInfo fileInfo = new FileInfo(item);

                    sourceList_dataGrid1.Add(fileInfo);
                }

                dataGrid1.ItemsSource = sourceList_dataGrid1.OrderBy(x=>x.LastWriteTime);
                
                #endregion

            }
            catch (Exception)
            {
                throw;
            }
            

        }

        public static List<string> Getfiles(string filepath, string pattern,bool? childFolder)
        {
            string p = pattern;

            List<string> f_name_list = new List<string>();

            if (childFolder==true)
            {
                f_name_list = System.IO.Directory.GetFiles(filepath, p, System.IO.SearchOption.AllDirectories).ToList<string>();
            }
            else
            {
                f_name_list = System.IO.Directory.GetFiles(filepath, p, System.IO.SearchOption.TopDirectoryOnly).ToList<string>();
            }
            return f_name_list;
        }

        private void ComBoxTime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (comBoxTime.SelectedIndex==0)
            //{
            //    startTimeDate.IsEnabled = false;
            //    endTimeDate.IsEnabled = false;
            //}
            //else
            //{
            //    startTimeDate.IsEnabled = true;
            //    endTimeDate.IsEnabled = true;

            //}
        }

        private void ListBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            FlowDocument fdoc = richTextBox.Document;

            Paragraph paragraph = new Paragraph();
            
            string filePath = listBox1.SelectedItem.ToString();

            richTextBox.Document.Blocks.Clear();

            if (System.IO.File.Exists(filePath))
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

                Run run1 = new Run("文件修改时间" + "\r\n" + fileInfo.LastAccessTime.Date.ToLocalTime()+ "\r\n");
                
                run1.Foreground = Brushes.Black;

                paragraph.Inlines.Add(run1);

                Run run2 = new Run("文件创建时间" + "\r\n" + fileInfo.CreationTime.Date + "\r\n");

                run2.Foreground = Brushes.Black;

                paragraph.Inlines.Add(run2);

                Run run3 = new Run("文件大小(Mb)" + "\r\n" + (fileInfo.Length/1024.0/1024.0).ToString("F3") + "\r\n");

                run3.Foreground = Brushes.Black;

                paragraph.Inlines.Add(run3);





                richTextBox.Document.Blocks.Add(paragraph);

                richTextBox.ScrollToEnd();
                
            }



        }

        private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            FileInfo fi = dataGrid1.SelectedItem as FileInfo;


            if (fi == null)
            {
                return;
            }

            //下边写用richtextbox的情况

            FlowDocument fdoc = richTextBox.Document;

            //fdoc.Blocks.Clear();

            Paragraph paragraph = new Paragraph();

            Run run1 = new Run("File:" + fi.Name + "\r\n");

            run1.Foreground = Brushes.Black;

            Run run2 = new Run("最后写入时间:" + "\r\n");

            run2.Foreground = Brushes.Black;

            run2.FontWeight = FontWeights.Bold;

            Run run3 = new Run(fi.LastWriteTime.ToString()+ "\r\n");

            run3.Foreground = Brushes.Red;

            run3.FontWeight = FontWeights.Bold;

            Run run4 = new Run("文件创建时间:" + "\r\n");

            run4.Foreground = Brushes.Black;
            run4.FontWeight = FontWeights.Bold;

            Run run5 = new Run(fi.CreationTime.ToString() + "\r\n");

            run5.Foreground = Brushes.Red;
            run5.FontWeight = FontWeights.Bold;

            paragraph.Inlines.Add(run1);

            paragraph.Inlines.Add(run2);

            paragraph.Inlines.Add(run3);

            paragraph.Inlines.Add(run4);

            paragraph.Inlines.Add(run5);

            richTextBox.Document.Blocks.Add(paragraph);

            richTextBox.ScrollToEnd();

            scrollViewer1.ScrollToBottom();



        }

        private void DataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            FileInfo fileInfo = e.Row.Item as FileInfo;

           
            

            //MyFileInfo myFileInfo = e.Row.Item as MyFileInfo;
            //if (myFileInfo.Tag % 2 == 0)
            //{
            //    e.Row.Background = new SolidColorBrush(Colors.White);
            //}
            //else
            //{

            //    e.Row.Background = new SolidColorBrush(Colors.PaleTurquoise);

            //}

        }

        private void DataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            FileInfo myFileInfo = dataGrid1.SelectedItem as FileInfo;

            if (myFileInfo != null)
            {
                string file_Name = myFileInfo.FullName;

                string tmp_path = System.IO.Path.GetDirectoryName(file_Name);

                System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);
            }

        }



  

    }
}
